//
//  ReadStoryViewController.m
//  图片故事
//
//  Created by 刘鉴古 on 16/3/1.
//  Copyright © 2016年 helloApp. All rights reserved.
//

#import "ReadStoryViewController.h"
#import "CombinationCell.h"
#import "FL_WaterFallLayout.h"
#import "ReadDetailViewController.h"
#import "CreateManagerViewController.h"
#import "ListTableViewCell.h"
#import "MJRefresh.h"
#import <BmobSDK/Bmob.h>
#import "UIImageView+WebCache.h"
#import "ReadDetailViewController.h"
#import "Header.h"

//#import "UIScrollView+MJRefresh.h"
@interface ReadStoryViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,FL_WaterFallLayoutDelegate,UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UITableView *listTableView;
@property (nonatomic, assign) BOOL selecd;
@property (nonatomic, strong) NSMutableArray *array;
@property (nonatomic, strong) UIButton *rightBtn;
@property (nonatomic, strong) UIImage *image;

@end
#define Screen self.view.bounds.size
@implementation ReadStoryViewController

-(UITableView *)listTableView{
    if (!_listTableView) {
        _listTableView = [[UITableView alloc] init];
        _listTableView.frame = CGRectMake(0, self.navigationController.navigationBar.bounds.size.height + My_Height(20), Screen.width, Screen.height - self.navigationController.navigationBar.bounds.size.height - My_Height(20));
        _listTableView.delegate = self;
        _listTableView.dataSource = self;
        
        [_listTableView setBackgroundColor:Bg_Color];
        
        [_listTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        
        [_listTableView registerClass:[ListTableViewCell class] forCellReuseIdentifier:@"tableViewCell"];
        
        [self.listTableView.mj_header endRefreshing];
    }
    return _listTableView;
}


- (void)viewDidLoad {
    self.automaticallyAdjustsScrollViewInsets = NO;
    [super viewDidLoad];
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    _array = [[NSMutableArray alloc] init];
    
    [self initCombinationCellData];
    [self initNavigation];
   
    [self initCollectionView];
    [self collectionViewRefresh];
    
}
-(void)collectionViewRefresh{
    __weak typeof(self) weakSelf = self;
    // 下拉刷新
    self.collectionView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf initCombinationCellData];
        
        [weakSelf.collectionView reloadData];
        
        [weakSelf.collectionView.mj_header endRefreshing];
    }];
    [weakSelf.collectionView.mj_header beginRefreshing];
    
    
}
-(void)tableViewRefresh{
    __weak typeof(self) weakSelf = self;
    // 下拉刷新
    self.listTableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf initCombinationCellData];
        [weakSelf.collectionView reloadData];
        [weakSelf.listTableView.mj_header endRefreshing];
    }];
    [self.listTableView.mj_header beginRefreshing];
}
- (void) initNavigation {
    
    [self.navigationController.navigationBar setBarTintColor:[UIColor blackColor]];
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor], NSFontAttributeName : [UIFont systemFontOfSize:20]}];
    
    self.title = @"图文生活";
    
    
    // 设置导航控制器左右按钮
    UIBarButtonItem *backItme = [[UIBarButtonItem alloc] initWithTitle:@"返回 " style:UIBarButtonItemStylePlain target:self action:@selector(action_backItmeClickEvent)];
    
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    
    self.navigationItem.leftBarButtonItem = backItme;
    
    
    _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _rightBtn.frame = CGRectMake(Screen.width - My_Width(50), My_Height(29),  My_Height(30), My_Height(30));
    [_rightBtn setImage:[UIImage imageNamed:@"grid.png"] forState:UIControlStateNormal];
    [_rightBtn addTarget:self action:@selector(action_changeModel:) forControlEvents:
     UIControlEventTouchUpInside];
    
    [self.navigationController.view addSubview:_rightBtn];
    
}
- (void) action_changeModel :(UIButton *) sender{
    if (_selecd == YES) {

        [UIView animateWithDuration:1.0 animations:^{
            [sender setImage:[UIImage imageNamed:@"grid.png"] forState:UIControlStateNormal];
        }];
        
        [_listTableView removeFromSuperview];
        
        [self initCollectionView];
        
        [self collectionViewRefresh];
        
        
        
    }else{
        
        [UIView animateWithDuration:1.0 animations:^{
            [sender setImage:[UIImage imageNamed:@"list.png"] forState:UIControlStateNormal];
        }];
        
        [_collectionView removeFromSuperview];
        
        [self initListTableView];
        
        [self tableViewRefresh];
        
    }
    _selecd = !_selecd;
}
/* - - - - - -- - - - - - - - -页面相关设置 - - - - - - - - - -- -  */
-(void)initListTableView{
    [self.view addSubview:self.listTableView];
    
}
-(void)initCollectionView{
    
    
    FL_WaterFallLayout *waterFlow = [[FL_WaterFallLayout alloc]init];
    waterFlow.delegate = self;
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:waterFlow];
    self.collectionView.frame = CGRectMake(0, 64, Screen.width, Screen.height - 64);
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView setBackgroundColor:Bg_Color];
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerClass:[CombinationCell class] forCellWithReuseIdentifier:@"CombinationCell"];
    
    [self.collectionView.mj_header endRefreshing];
}

-(CGFloat)waterFlowLayout:(FL_WaterFallLayout *)waterFlowLayout heightForWidth:(CGFloat)width indexPath:(NSIndexPath *)indexPath{
    
    NSString *imageWidth = [[self.array objectAtIndex:indexPath.row] objectForKey:@"imageWidth"];
    
    NSString *imageHeight = [[self.array objectAtIndex:indexPath.row] objectForKey:@"imageHeight"];
    
    return [imageHeight intValue] * SCREEN_W / 2 / [imageWidth intValue];

}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return self.array.count;
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CombinationCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CombinationCell" forIndexPath:indexPath];
    
    BmobObject *obj = self.array[indexPath.row];
    
    NSString *name = [obj objectForKey:@"imageStoryName"];
    
    cell.titleLabel.text = [NSString stringWithFormat:@"  %@",name];
    
//    NSString *time = [obj objectForKey:@"createdAt"];
//    cell.creatTimeLabel.text = time;
    
    NSString *image = [obj objectForKey:@"imageStoryImage"];
    
    [cell.themeImageView sd_setImageWithURL:[NSURL URLWithString:image] placeholderImage:[UIImage imageNamed:@"meinv.jpg"]];

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return My_Height(240);
}

- (void)initCombinationCellData{
    
    dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        BmobQuery   *bquery = [BmobQuery queryWithClassName:@"imageStory"];
        //查找GameScore表的数据
        __weak typeof(self) weakSelf = self;
        [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
            
            weakSelf.array = (NSMutableArray *)[[array reverseObjectEnumerator] allObjects];
            
            [weakSelf.collectionView reloadData];
        }];
    });
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ReadDetailViewController *detailVc =[[ReadDetailViewController alloc] init];

    BmobObject *obj = self.array[indexPath.row];
    
    detailVc.selectObject  = obj;
    
    [self.navigationController pushViewController:detailVc animated:YES];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.array.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableViewCell"];
    
    if (!cell) {
        
        cell = [[ListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"tableViewCell"];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    BmobObject *obj = self.array[indexPath.row];
    
    NSString *title = [obj objectForKey:@"imageStoryName"];
    cell.titleLabel.text = title;
    
    NSString *time = [obj objectForKey:@"createdAt"];
    cell.timeLabel.text = time;
    
    NSString *image = [obj objectForKey:@"imageStoryImage"];
    [cell.detailImage sd_setImageWithURL:[NSURL URLWithString:image] placeholderImage:[UIImage imageNamed:@"meinv.jpg"]];
    
    NSString *map = [obj objectForKey:@"imageStoryLocation"];
    cell.mapLabel.text = map;
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ReadDetailViewController *detailVc =[[ReadDetailViewController alloc] init];
    
    BmobObject *obj = self.array[indexPath.row];
    
    detailVc.selectObject  = obj;
    
    [self.navigationController pushViewController:detailVc animated:YES];
}

- (void) action_backItmeClickEvent {

    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewWillDisappear:(BOOL)animated {

    [_rightBtn removeFromSuperview];
}

- (void)viewWillAppear:(BOOL)animated {

    [self.navigationController.view addSubview:_rightBtn];
}
@end
